package de.preisrobot.service.internal;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import de.preisrobot.entity.AmazonArtikelImage;
import de.preisrobot.service.helper.HttpClientFactory;

public class AmazonImageGrabber {
   
   private static Logger logger = Logger.getLogger(AmazonImageGrabber.class);

	public AmazonArtikelImage getImage(String url) {
		
		AmazonArtikelImage image = null;
		BufferedInputStream buffIn  =null;
		GetMethod method =null;
		try {
			
			HttpClient client = HttpClientFactory.getHttpClient();
			method = HttpClientFactory.createGETMethod(url);
			client.executeMethod(method);
			
			buffIn = new BufferedInputStream( method.getResponseBodyAsStream());
			ByteArrayOutputStream bos = new ByteArrayOutputStream();

			int c = -1;
	
			while( (c=  buffIn.read()) != -1)
			{
				bos.write(c);
			}
			buffIn.close();

			image = new AmazonArtikelImage();
			image.setImage(bos.toByteArray() );
 
		} catch (Exception e) {

		   logger.warn(url +" "+e.getMessage());
//			e.printStackTrace();
		}
		finally{
			
			if(method!=null)
				method.releaseConnection();
		}

		return image;
	}

	private byte[] copyBytes(byte[] b) {
		 
		long size  = determineBufferSize(b);
		System.out.println("filesize"+size);
		byte[] a = new byte[(int) size];
		for(int i=0; i<size;i++)
			a[i] = b[i];
		return a;
	}

	private long determineBufferSize(byte[] b) {
		
		for(int i=0;i<b.length;i++)
		{
			if(b[i] == -1)
				return i;
		}

		return 0;
	}

}
